// file_writter_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

bool GenerateFixedSizeFile(stringc& strDir, stringc& strFile);
_CZ_FILE_RESULT WINAPI DoBrowseDirFixedSize(string& strPath, void* pUserData);

bool GenerateVariableSizeFile(stringc& strDir, stringc& strFile);
_CZ_FILE_RESULT WINAPI DoBrowseDirVariableSize(string& strPath, void* pUserData);

int _tmain(int argc, _TCHAR* argv[])
{
	string strDir, strFile;

	// you can change the directory to your own
	strDir = cz_file_GetExeDirA() + "..\\..\\..\\";

	strFile = cz_file_GetExeDirA() + "..\\Data\\fixed.bin";
	if (!GenerateFixedSizeFile(strDir, strFile))
	{
		cout << "GenerateFixedSizeFile failed" << endl;
		getchar();
		return 0;
	}
	cout << "GenerateFixedSizeFile success" << endl;

	strFile = cz_file_GetExeDirA() + "..\\Data\\variable.bin";
	if (!GenerateVariableSizeFile(strDir, strFile))
	{
		cout << "GenerateVariableSizeFile failed" << endl;
		getchar();
		return 0;
	}
	cout << "GenerateVariableSizeFile success" << endl;

	cout << "ok" << endl;
	getchar();

	return 0;
}

bool GenerateFixedSizeFile(stringc& strDir, stringc& strFile)
{
	FileWritterPool fwp;

	if (!fwp.Init(strFile, 1 * 1024 * 1024)) return false;		// 1M
	if (!cz_file_BrowseDirA(strDir, DoBrowseDirFixedSize, &fwp)) return false;
	if (!fwp.ForceToWrite()) return false;
	fwp.Uninit();

	return true;
}

_CZ_FILE_RESULT WINAPI DoBrowseDirFixedSize(string& strPath, void* pUserData)
{
	FileWritterPool* pfwp = (FileWritterPool*)pUserData;
	char buf[CZ_MAX_PATHA + 1];
	memset(buf, 0, CZ_MAX_PATHA + 1);
	memcpy(buf, strPath.c_str(), strPath.size());
	if (!pfwp->WriteData(reinterpret_cast<u8c* >(buf), CZ_MAX_PATHA + 1))
	{
		CZ_LOG_ERRORA("");
		return CZ_FILE_ERROR;
	}
	return CZ_FILE_DEFAULT;
}

bool GenerateVariableSizeFile(stringc& strDir, stringc& strFile)
{
	FileWritterPool fwp;

	if (!fwp.Init(strFile, 1 * 1024 * 1024))		// 1M
	{
		CZ_LOG_ERRORA("");
		return false;
	}
	if (!cz_file_BrowseDirA(strDir, DoBrowseDirVariableSize, &fwp))
	{
		CZ_LOG_ERRORA("");
		return false;
	}
	if (!fwp.ForceToWrite())
	{
		CZ_LOG_ERRORA("");
		return false;
	}
	fwp.Uninit();

	return true;
}

_CZ_FILE_RESULT WINAPI DoBrowseDirVariableSize(string& strPath, void* pUserData)
{
	FileWritterPool* pfwp = (FileWritterPool*)pUserData;
	if (!pfwp->Writeu32(strPath.size() + 1))
	{
		CZ_LOG_ERRORA("");
		return CZ_FILE_ERROR;
	}
	if (!pfwp->WriteData(reinterpret_cast<u8c* >(strPath.c_str()), strPath.size() + 1))
	{
		CZ_LOG_ERRORA("");
		return CZ_FILE_ERROR;
	}
	return CZ_FILE_DEFAULT;
}

